<template>
  <div class="design-editor-container">
    <!-- 简化后的编辑器布局 -->
    <div class="editor-main">
      <!-- 左侧工具栏 -->
      <div class="editor-sidebar" :class="{ 'collapsed': sidebarCollapsed }">
        <div class="sidebar-header">
          <h3>AI绘画平台</h3>
          <button class="collapse-btn" @click="toggleSidebar">
            {{ sidebarCollapsed ? '›' : '‹' }}
          </button>
        </div>
        <div class="sidebar-content" v-if="!sidebarCollapsed">
          <!-- 工具选项卡 -->
          <div class="tool-tabs">
            <div class="tab" :class="{active: activeTab === 'template'}" @click="activeTab = 'template'">模板</div>
            <div class="tab" :class="{active: activeTab === 'text'}" @click="activeTab = 'text'">文字</div>
            <div class="tab" :class="{active: activeTab === 'material'}" @click="activeTab = 'material'">素材</div>
            <div class="tab" :class="{active: activeTab === 'preview'}" @click="activeTab = 'preview'">预览</div>
            <div class="tab" :class="{active: activeTab === 'layers'}" @click="activeTab = 'layers'">图层</div>
          </div>
          
          <!-- 工具内容区 -->
          <div class="tool-content">
            <!-- 模板选项卡内容 (使用组件) -->
        <TemplatePanel 
          v-if="activeTab === 'template'" 
          @select-ratio="handleCanvasResize"
        />
        
           
        
            <!-- 使用TextPanel组件替换 -->
        <TextPanel 
              v-else-if="activeTab === 'text'"
              :fontFamily="textSettings.fontFamily"
              :fontSize="textSettings.fontSize"
              :color="textSettings.color"
              @add-text="addNewText"
              @add-gradient-text="addGradientText"
              @format-text="formatText"
              @update-style="handleTextStyleUpdate"
            />

            <!-- 素材选项卡内容 (使用组件) -->
        <MaterialPanel 
              v-else-if="activeTab === 'material'"
              @add-shape="handleAddShape"
              @add-material="handleAddMaterial"
              @upload-image="handleUploadImage"
              @apply-background="handleApplyBackground"
              @background-gradient-change="handleBackgroundGradientChange"
              @background-image-change="handleBackgroundImageChange"
            />

            <!-- 预览选项卡内容 -->
            <div v-else-if="activeTab === 'preview'">
              <h4 class="section-title">预览设备</h4>
              <div class="device-grid">
                <div class="device-item" :class="{active: previewDevice === 'desktop'}" @click="previewDevice = 'desktop'">
                  <div class="device-icon desktop-icon"></div>
                  <span>桌面端</span>
                  <div class="device-size">1920 × 1080</div>
        </div>
                <div class="device-item" :class="{active: previewDevice === 'tablet'}" @click="previewDevice = 'tablet'">
                  <div class="device-icon tablet-icon"></div>
                  <span>平板</span>
                  <div class="device-size">768 × 1024</div>
      </div>
                <div class="device-item" :class="{active: previewDevice === 'mobile'}" @click="previewDevice = 'mobile'">
                  <div class="device-icon mobile-icon"></div>
                  <span>手机</span>
                  <div class="device-size">375 × 667</div>
          </div>
          </div>
              
              <h4 class="section-title">导出设置</h4>
              <div class="export-controls">
                <div class="input-group">
                  <label>格式</label>
                  <select v-model="exportSettings.format">
                    <option value="png">PNG (透明背景)</option>
                    <option value="jpg">JPG</option>
                    <option value="pdf">PDF</option>
                  </select>
        </div>
        
                <div class="input-group">
                  <label>质量: {{exportSettings.quality}}%</label>
                  <input type="range" min="1" max="100" v-model="exportSettings.quality" />
          </div>
                
                <div class="size-inputs">
                  <div class="input-group half">
                  <label>宽度:</label>
                    <input type="number" v-model="exportSettings.width" />
          </div>
                  <div class="input-group half">
                    <label>高度:</label>
                    <input type="number" v-model="exportSettings.height" />
        </div>
      </div>
      
                <div class="checkbox-group">
                  <input type="checkbox" id="keep-ratio" v-model="exportSettings.maintainRatio" />
                  <label for="keep-ratio">保持宽高比例</label>
          </div>
                
                <button class="preview-btn" @click="openPreview">在新窗口预览</button>
                <button class="export-btn" @click="exportDesign">导出设计</button>
          </div>
        </div>
        
            <!-- 使用PreviewPanel组件 -->
            <PreviewPanel 
              v-else-if="activeTab === 'preview'"
              :preview-device="previewDevice"
              :device-dimensions="deviceDimensions"
              :export-format="exportSettings.format"
              :export-quality="Number(exportSettings.quality)"
              :export-width="Number(exportSettings.width)"
              :export-height="Number(exportSettings.height)"
              :maintain-aspect-ratio="exportSettings.maintainRatio"
              @device-change="previewDevice = $event"
              @format-change="exportSettings.format = $event"
              @quality-change="exportSettings.quality = Number($event)"
              @dimension-change="handleExportDimensionChange"
              @ratio-change="exportSettings.maintainRatio = $event"
              @open-preview="openPreview"
              @export-design="exportDesign"
            />

            <!-- 图层选项卡内容 -->
            <div v-else-if="activeTab === 'layers'">
              <h4 class="section-title">图层管理</h4>
              <div class="layers-container">
                <!-- 使用 canvasLayers 替代静态 layers -->
                <div class="layer-item" v-for="(layer, index) in canvasLayers" :key="layer.id" 
                     :class="{ 'layer-selected': layer.selected }">
                  <div class="layer-visibility">
                    <i class="fas fa-eye" v-if="layer.visible" @click="toggleLayerVisibility(index)"></i>
                    <i class="fas fa-eye-slash" v-else @click="toggleLayerVisibility(index)"></i>
                </div>
                  <div class="layer-name" @click="selectLayer(index)">{{ layer.name }}</div>
                  <div class="layer-actions">
                    <i class="fas" :class="[layer.locked ? 'fa-lock' : 'fa-lock-open']" 
                       @click="toggleLayerLock(index)" 
                       :title="layer.locked ? '解锁图层' : '锁定图层'"></i>
                    <i class="fas fa-trash-alt" @click="deleteLayer(index)"></i>
                </div>
                </div>
                <div class="layer-empty" v-if="!canvasLayers || canvasLayers.length === 0">
                  <p>没有图层</p>
              </div>
                </div>
                </div>
      </div>
                </div>
              </div>
              
      <!-- 中间画布区域 -->
      <div class="canvas-area">
        <!-- 顶部工具栏 -->
        <EditorToolbar 
          :has-selection="!!selectedObject"
          :has-multiple-selection="selectedObject && selectedObject.type === 'activeSelection'"
          :is-locked="isLocked"
          :is-group="isGroup"
          :show-grid="showGrid"
          :show-ruler="showRuler"
          :show-guides="showGuides"
          :zoom-level="zoomLevel"
          @mode-change="setMode"
          @cut-object="cutObject"
          @copy-object="copyObject"
          @delete-object="deleteObject"
          @align-objects="alignObjects"
          @distribute-objects="distributeObjects"
          @arrange-layer="arrangeLayer"
          @toggle-lock="toggleLock"
          @toggle-group="toggleGroup"
          @flip-object="flipObject"
          @clone-object="cloneObject"
          @toggle-grid="toggleGrid"
          @toggle-ruler="toggleRuler"
          @toggle-guidelines="toggleGuidelines"
          @show-dimensions="showDimensions"
          @zoom-in="zoomIn"
          @zoom-out="zoomOut"
          @original-size="originalSize"
          @center-canvas="centerCanvas"
        />
        
        <!-- 画布容器 - 确保画布居中显示 -->
        <div class="canvas-wrapper" :class="{ 'with-ruler': showRuler }">
          <!-- 标尺容器元素 - 仅作为视觉参考，实际标尺由fabric绘制 -->
          <div class="ruler ruler-horizontal" v-if="showRuler"></div>
          <div class="ruler ruler-vertical" v-if="showRuler"></div>
          <div class="ruler-corner" v-if="showRuler"></div>
          <FabricEditor 
            ref="fabricEditorRef" 
            class="fabric-editor" 
            @canvas-ready="handleCanvasReady" 
            @zoom-changed="handleZoomChanged" 
          />
          <div class="canvas-info" v-if="showInfo">
            <div v-if="canvas">
              <p>画布大小: {{ workspaceWidth }} x {{ workspaceHeight }}</p>
              <p>缩放: {{ zoomLevel.toFixed(2) }}</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧属性面板 -->
      <div class="editor-properties" :class="{ 'collapsed': propertiesCollapsed }">
        <button class="collapse-btn right" @click="toggleProperties">
          {{ propertiesCollapsed ? '‹' : '›' }}
        </button>
        <div class="properties-content" v-if="!propertiesCollapsed">
          <!-- 右侧选项卡 -->
          <div class="right-panel-tabs">
            <div class="tab" :class="{ active: activeRightTab === 'properties' }" @click="activeRightTab = 'properties'">属性</div>
            <div class="tab" :class="{ active: activeRightTab === 'text2img' }" @click="activeRightTab = 'text2img'">文生图</div>
            <div class="tab" :class="{ active: activeRightTab === 'img2img' }" @click="activeRightTab = 'img2img'">图生图</div>
          </div>
          
          <!-- 选项卡内容区域 -->
          <div class="right-panel-content">
            <!-- 使用 PropertiesPanel 组件 -->
            <PropertiesPanel 
              v-if="activeRightTab === 'properties'" 
              :selected-object="selectedObject" 
              :request-render-prop="requestRender" 
              @update:text-settings="handleTextSettingsUpdate"
            />
            
            <!-- 文生图面板 -->
            <div v-else-if="activeRightTab === 'text2img'">
              <h4>文生图</h4>
              <p>这里是文生图的配置界面...</p>
            </div>
            
            <!-- 图生图面板 -->
            <div v-else-if="activeRightTab === 'img2img'">
              <h4>图生图</h4>
              <p>这里是图生图的配置界面...</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from 'vue';
import FabricEditor from '../components/FabricEditor.vue';
// 导入fabric库
// @ts-ignore
// import * as fabricModule from 'fabric';
// const fabric = fabricModule.fabric || fabricModule;
import { fabric } from 'fabric'; // Use named import

import PropertiesPanel from '@/components/editor/PropertiesPanel.vue'; // 引入新组件
import TemplatePanel from '@/components/editor/TemplatePanel.vue'; // 引入 TemplatePanel
import TextPanel from '@/components/editor/TextPanel.vue';
import MaterialPanel from '@/components/editor/MaterialPanel.vue'; // 引入 MaterialPanel
import EditorToolbar from '@/components/editor/EditorToolbar.vue'; // 引入工具栏组件
import PreviewPanel from '@/components/editor/PreviewPanel.vue'; // 引入预览面板组件

// 状态
const activeTab = ref('template');
const sidebarCollapsed = ref(false);
const showProperties = ref(true);
const showInfo = ref(true);
const activeRightTab = ref('properties');
const propertiesCollapsed = ref(false);

// 预览设备和导出设置
const previewDevice = ref('desktop');
const exportSettings = reactive({
  format: 'png',
  quality: 90,
  width: 800,
  height: 600,
  maintainRatio: true
});

// 文本设置
const textSettings = reactive({
  fontFamily: 'Arial',
  fontSize: 24,
  color: '#000000'
});

// 工具栏状态
const showGrid = ref(false);
const showRuler = ref(false);
const showGuides = ref(false);  // 新增：参考线显示状态
const isLocked = ref(false);
const isGroup = ref(false);

// 网格和标尺对象存储
const gridLines: any[] = [];
const rulerElements: any[] = [];

// 画布引用
const fabricEditorRef = ref<InstanceType<typeof FabricEditor> | null>(null);
const canvas = ref<any>(null);

// 画布尺寸变量
const workspaceWidth = ref(800);
const workspaceHeight = ref(600);

// 用于自定义尺寸
const customWidth = ref(800);
const customHeight = ref(600);

// 画布控制变量
const canvasWidth = ref(workspaceWidth.value);
const canvasHeight = ref(workspaceHeight.value);

// 画布设置
const zoomLevel = ref(1);
const selectedObject = ref<any>(null);

// resize防抖计时器
let resizeTimer: number | null = null;

// --- 图层管理功能 ---
// 图层数据
const canvasLayers = ref<Array<{id: string, name: string, visible: boolean, locked: boolean, selected: boolean}>>([]);

// 更新图层列表
function updateLayersList() {
  if (!canvas.value) return;
  
  const objects = canvas.value.getObjects();
  // 排除工作区本身
  const layerObjects = objects.filter((obj: fabric.Object) => obj.id !== 'workspace');
  
  // 构建图层数据
  canvasLayers.value = layerObjects.map((obj: fabric.Object) => {
    return {
      id: obj.id || generateRandomId(),
      name: obj.name || `图层 ${canvasLayers.value.length + 1}`,
      visible: !obj.invisible,
      locked: obj.lockMovementX && obj.lockMovementY,
      selected: obj === canvas.value.getActiveObject()
    };
  });
}

// 生成随机ID
function generateRandomId() {
  return 'layer_' + Math.random().toString(36).substr(2, 9);
}

// 图层可见性切换
function toggleLayerVisibility(index: number) {
  if (!canvas.value || !canvasLayers.value[index]) return;
  
  const objects = canvas.value.getObjects();
  const layerObjects = objects.filter((obj: fabric.Object) => obj.id !== 'workspace');
  
  if (layerObjects[index]) {
    canvasLayers.value[index].visible = !canvasLayers.value[index].visible;
    layerObjects[index].visible = canvasLayers.value[index].visible;
    
    if (!canvasLayers.value[index].visible) {
      layerObjects[index].set('opacity', 0);
    } else {
      layerObjects[index].set('opacity', 1);
    }
    
    canvas.value.renderAll();
    console.log(`图层 ${index} 可见性已切换`);
  }
}

// 图层锁定切换
function toggleLayerLock(index: number) {
  if (!canvas.value || !canvasLayers.value[index]) return;
  
  const objects = canvas.value.getObjects();
  const layerObjects = objects.filter((obj: fabric.Object) => obj.id !== 'workspace');
  
  if (layerObjects[index]) {
    canvasLayers.value[index].locked = !canvasLayers.value[index].locked;
    layerObjects[index].set('lockMovementX', canvasLayers.value[index].locked);
    layerObjects[index].set('lockMovementY', canvasLayers.value[index].locked);
    layerObjects[index].set('lockRotation', canvasLayers.value[index].locked);
    layerObjects[index].set('lockScalingX', canvasLayers.value[index].locked);
    layerObjects[index].set('lockScalingY', canvasLayers.value[index].locked);
    
    canvas.value.renderAll();
    console.log(`图层 ${index} 锁定状态已切换`);
  }
}

// 选择图层
function selectLayer(index: number) {
  if (!canvas.value || !canvasLayers.value[index]) return;
  
  const objects = canvas.value.getObjects();
  const layerObjects = objects.filter((obj: fabric.Object) => obj.id !== 'workspace');
  
  if (layerObjects[index]) {
    canvas.value.setActiveObject(layerObjects[index]);
    canvas.value.renderAll();
    
    // 更新选中状态
    canvasLayers.value.forEach((layer, i) => {
      layer.selected = i === index;
    });
    
    console.log(`已选择图层 ${index}`);
  }
}

// 删除图层
function deleteLayer(index: number) {
  if (!canvas.value || !canvasLayers.value[index]) return;
  
  const objects = canvas.value.getObjects();
  const layerObjects = objects.filter((obj: fabric.Object) => obj.id !== 'workspace');
  
  if (layerObjects[index]) {
    canvas.value.remove(layerObjects[index]);
    canvasLayers.value.splice(index, 1);
    canvas.value.renderAll();
    console.log(`已删除图层 ${index}`);
  }
}

// 属性面板折叠切换
function toggleProperties() {
  propertiesCollapsed.value = !propertiesCollapsed.value;
}

// 处理文本设置更新
function handleTextSettingsUpdate(settings: any) {
  console.log('接收到文本设置更新:', settings);
  handleTextStyleUpdate(settings);
}

// 当画布对象发生变化时更新图层列表
function handleCanvasChanged() {
  updateLayersList();
}

// 监听画布事件 - 在初始化和对象变化时更新图层
function setupLayerSync() {
  if (!canvas.value) return;
  
  // 监听选择变化
  canvas.value.on('selection:created', handleCanvasChanged);
  canvas.value.on('selection:updated', handleCanvasChanged);
  canvas.value.on('selection:cleared', handleCanvasChanged);
  
  // 监听对象添加/移除
  canvas.value.on('object:added', handleCanvasChanged);
  canvas.value.on('object:removed', handleCanvasChanged);
  
  // 监听对象修改
  canvas.value.on('object:modified', handleCanvasChanged);
}

// 初始化画布 - 移除直接获取canvas的逻辑
function initCanvas() {
  console.log('等待 FabricEditor 发出 canvas-ready 事件...');
  // 重置元素计数器
  resetElementCounter();
}

// 新增：处理子组件画布就绪事件
function handleCanvasReady(fabricCanvas: fabric.Canvas) {
  console.log('画布已准备就绪', fabricCanvas);
  
  // 保存画布引用
  canvas.value = fabricCanvas;
  
  // 初始化画布尺寸
  if (fabric) {
    initCanvas();
  }
  
  // 设置图层同步
  setupLayerSync();
  
  // 初始更新图层列表
  updateLayersList();
  
  // 设置对象选择事件监听
  canvas.value.on('selection:created', handleObjectSelected);
  canvas.value.on('selection:updated', handleObjectSelected);
  canvas.value.on('selection:cleared', handleSelectionCleared);
  
  // 如果标尺状态为显示，则绘制标尺
  if (showRuler.value) {
    nextTick(() => {
      console.log('画布就绪后，检测到标尺状态为显示，开始绘制');
      drawRulers();
    });
  }
}

// 居中画布
function centerCanvas() {
  // 检查 canvas.value 是否有效
  if (!canvas.value) {
    console.warn('centerCanvas 调用时 canvas.value 无效');
    // 可以选择尝试通过 ref 再次调用子组件的方法，但这可能引入复杂性
    // 推荐的方式是确保 handleCanvasReady 之后才调用依赖 canvas.value 的函数
    if (fabricEditorRef.value) {
       console.log('尝试通过 ref 调用子组件 centerCanvas');
       fabricEditorRef.value.centerCanvas(); 
       // 更新 zoomLevel 仍然需要 canvas.value
       // zoomLevel.value = canvas.value?.getZoom() ?? zoomLevel.value;
    }
            return;
          }
          
  // 原有的居中逻辑，现在依赖本地的 canvas.value
  // ... (需要从 FabricEditor.vue 复制/调整相关居中逻辑)
  // 或者更简单：继续通过 ref 调用子组件方法
  if (fabricEditorRef.value) {
    fabricEditorRef.value.centerCanvas();
    zoomLevel.value = canvas.value.getZoom(); // 现在可以安全访问
  }
  
  console.log('画布已居中显示 (通过 handleCanvasReady 或 ref)');
}

// 放大
function zoomIn() {
  if (!canvas.value) {
     console.error('无法缩放：画布实例无效');
          return;
  }
  // 通过 ref 调用子组件方法仍然可行，且更简单
  if (!fabricEditorRef.value) return;
  fabricEditorRef.value.zoomIn();
  zoomLevel.value = canvas.value.getZoom();
}

// 缩小
function zoomOut() {
  if (!canvas.value) {
     console.error('无法缩放：画布实例无效');
     return;
  }
  // 通过 ref 调用子组件方法仍然可行，且更简单
  if (!fabricEditorRef.value) return;
  fabricEditorRef.value.zoomOut();
  zoomLevel.value = canvas.value.getZoom();
}

// 原始大小
function originalSize() {
  if (!canvas.value) {
     console.error('无法缩放：画布实例无效');
          return;
  }
  // 通过 ref 调用子组件方法仍然可行，且更简单
  if (!fabricEditorRef.value) return;
  fabricEditorRef.value.zoomToActualSize();
  zoomLevel.value = canvas.value.getZoom();
  console.log("33=================zoomLevel.value", zoomLevel.value);
}

// 切换侧边栏
function toggleSidebar() {
  sidebarCollapsed.value = !sidebarCollapsed.value;
}

// 创建空白画布
function createBlankCanvas() {
  if (!canvas.value) return;
  
  console.log('创建空白画布...');
  
  // 保存当前标尺状态
  const wasRulerShown = showRuler.value;
  
  // 如果标尺已显示，先清除
  if (wasRulerShown) {
    console.log('创建新画布前清除现有标尺');
    clearRulers();
  }
  
  // 清除画布
  canvas.value.clear();
  console.log('画布已清除');
  
  if (fabricEditorRef.value) {
    console.log(`设置画布尺寸: ${workspaceWidth.value}x${workspaceHeight.value}`);
    fabricEditorRef.value.setCanvasSize(workspaceWidth.value, workspaceHeight.value);
  }
  
  // 重新居中
  centerCanvas();
  console.log('画布已居中');
  
  // 如果之前标尺是显示的，重新绘制
  if (wasRulerShown && showRuler.value) {
    console.log('创建新画布后重新绘制标尺');
    nextTick(() => {
      drawRulers();
    });
  }
  
  console.log('空白画布创建完成');
}

// 添加测试图形
function addTestRect() {
  if (!fabricEditorRef.value) return;
  
  fabricEditorRef.value.addTestRectangle();
}
    
    // 添加矩形
function addNewRect() {
  console.log('尝试添加矩形，当前画布实例:', canvas.value); // 在添加前打印 canvas.value
  if (!canvas.value) {
    console.error('错误：无法添加矩形，因为 canvas.value 无效！');
        return;
      }
      
      // 获取下一个元素位置
      const position = getNextElementPosition();
      
      const rect = new fabric.Rect({
    left: position.left,
    top: position.top,
        width: 100,
        height: 100,
    fill: '#3f51b5',
    stroke: '#1a237e',
    strokeWidth: 1,
    originX: 'left',
    originY: 'top',
    name: '矩形'
    // 设置初始 opacity 为 1
    // opacity: 1 // Fabric 对象默认 opacity 就是 1，通常无需显式设置
      });
      
  try {
    canvas.value.add(rect);
    canvas.value.setActiveObject(rect); // 选中新添加的矩形
    canvas.value.renderAll();
    console.log(`添加矩形，位置(${position.left}, ${position.top})`);
  } catch (e) {
    console.error('添加矩形到画布时出错:', e);
  }
}
    
    // 添加圆形
function addNewCircle() {
  console.log('尝试添加圆形，当前画布实例:', canvas.value); // 在添加前打印 canvas.value
  if (!canvas.value) {
    console.error('错误：无法添加圆形，因为 canvas.value 无效！');
        return;
      }
      
      // 获取下一个元素位置
      const position = getNextElementPosition();
      
      const circle = new fabric.Circle({
    left: position.left,
    top: position.top,
        radius: 50,
    fill: '#e91e63',
    stroke: '#880e4f',
    strokeWidth: 1,
    originX: 'left',
    originY: 'top',
    name: '圆形'
      });
      
  canvas.value.add(circle);
  canvas.value.setActiveObject(circle);
  canvas.value.renderAll();
  console.log(`添加圆形，位置(${position.left}, ${position.top})`);
}

// 更新画布大小
function updateCanvasSize() {
  if (!fabricEditorRef.value) return;
  
  workspaceWidth.value = canvasWidth.value;
  workspaceHeight.value = canvasHeight.value;
  
  fabricEditorRef.value.setCanvasSize(workspaceWidth.value, workspaceHeight.value);
  centerCanvas();
}

// 处理窗口大小变化
function handleResize() {
  if (resizeTimer) {
    clearTimeout(resizeTimer);
  }
  
  resizeTimer = window.setTimeout(() => {
    console.log('窗口大小变化，调整画布大小');
    if (fabricEditorRef.value) {
      centerCanvas();
    }
  }, 200);
}

// 生命周期钩子
onMounted(() => {
  console.log('SimpleEditorView组件已挂载');
  
  // 确保在DOM完全渲染后初始化Canvas
  nextTick(() => {
    console.log('DOM已更新，开始初始化Canvas');
    initCanvas();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
  });
});

onUnmounted(() => {
  console.log('SimpleEditorView unmounting...');
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize);
  
  // 安全地销毁 Fabric 画布
  if (canvas.value && typeof canvas.value.dispose === 'function') {
    console.log('Disposing Fabric canvas...');
    try {
      canvas.value.dispose();
      console.log('Fabric canvas disposed.');
    } catch (err) {
       console.error('Error disposing canvas:', err);
    }
  } else {
     console.warn('Canvas instance not available or invalid for disposal.');
  }
  canvas.value = null; // 明确设为 null
});

// 设置工具模式
function setMode(mode: string) {
  console.log(`设置模式: ${mode}`);
  // TODO: 实现模式切换逻辑
}

// 剪切对象
function cutObject() {
  if (!canvas.value || !selectedObject.value) return;
  
  // 先复制再删除
  copyObject();
  deleteObject();
  
  console.log('剪切对象');
}

// 复制对象
function copyObject() {
  if (!canvas.value || !selectedObject.value) return;
  
  console.log('复制对象');
  // TODO: 实现复制逻辑
}

// 删除对象
function deleteObject() {
  if (!canvas.value || !selectedObject.value) return;
  
  canvas.value.remove(selectedObject.value);
  canvas.value.renderAll();
  selectedObject.value = null;
  
  console.log('删除对象');
}

// 对齐对象
function alignObjects(direction: string) {
  if (!canvas.value) return;
  
  const activeObject = canvas.value.getActiveObject();
  if (!activeObject) return;
  
  // 获取画布区域的尺寸和位置
  // 注意：画布区域通常是一个可见的矩形，代表编辑区域
  // 画布区域通常会在初始化时创建为一个矩形
  const canvasArea = canvas.value.getObjects().find(
    (obj: any) => obj.id === 'canvas-area' || obj.name === '画布区域'
  ) as fabric.Object;
  
  // 如果找不到专门的画布区域对象，尝试找编辑区域或工作区
  let editArea = canvasArea;
  if (!editArea) {
    editArea = canvas.value.getObjects().find(
      (obj: any) => 
        obj.id === 'canvas-background' || 
        obj.name === '画布背景' || 
        obj.id === 'workspace' || 
        obj.name === '工作区'
    ) as fabric.Object;
  }
  
  // 如果仍然找不到，使用画布的可视区域大小
  const bounds = editArea ? {
    left: editArea.left || 0,
    top: editArea.top || 0,
    right: (editArea.left || 0) + (editArea.width || 0) * (editArea.scaleX || 1),
    bottom: (editArea.top || 0) + (editArea.height || 0) * (editArea.scaleY || 1),
    centerX: (editArea.left || 0) + ((editArea.width || 0) * (editArea.scaleX || 1)) / 2,
    centerY: (editArea.top || 0) + ((editArea.height || 0) * (editArea.scaleY || 1)) / 2
  } : {
    // 使用画布的可视区域
    left: 0,
    top: 0,
    right: workspaceWidth.value,
    bottom: workspaceHeight.value,
    centerX: workspaceWidth.value / 2,
    centerY: workspaceHeight.value / 2
  };
  
  // 记录对齐的边界信息
  console.log('对齐边界:', bounds);
  
  let value;
  switch (direction) {
    case 'left':
      value = bounds.left;
      break;
    case 'center':
      value = bounds.centerX;
      break;
    case 'right':
      value = bounds.right;
      break;
    case 'top':
      value = bounds.top;
      break;
    case 'middle':
      value = bounds.centerY;
      break;
    case 'bottom':
      value = bounds.bottom;
      break;
  }
  
  if (['left', 'center', 'right'].includes(direction)) {
    if (activeObject.type === 'activeSelection') {
      const group = activeObject;
      group.forEachObject((obj) => {
        const objWidth = obj.getScaledWidth();
        switch (direction) {
          case 'left':
            obj.set('left', value);
            break;
          case 'center':
            obj.set('left', value - objWidth / 2);
            break;
          case 'right':
            obj.set('left', value - objWidth);
            break;
        }
      });
    } else {
      const objWidth = activeObject.getScaledWidth();
      switch (direction) {
        case 'left':
          activeObject.set('left', value);
          break;
        case 'center':
          activeObject.set('left', value - objWidth / 2);
          break;
        case 'right':
          activeObject.set('left', value - objWidth);
          break;
      }
    }
  } else {
    if (activeObject.type === 'activeSelection') {
      const group = activeObject;
      group.forEachObject((obj) => {
        const objHeight = obj.getScaledHeight();
        switch (direction) {
          case 'top':
            obj.set('top', value);
            break;
          case 'middle':
            obj.set('top', value - objHeight / 2);
            break;
          case 'bottom':
            obj.set('top', value - objHeight);
            break;
        }
      });
    } else {
      const objHeight = activeObject.getScaledHeight();
      switch (direction) {
        case 'top':
          activeObject.set('top', value);
          break;
        case 'middle':
          activeObject.set('top', value - objHeight / 2);
          break;
        case 'bottom':
          activeObject.set('top', value - objHeight);
          break;
      }
    }
  }
  
  activeObject.setCoords();
  canvas.value.renderAll();
  console.log(`已对齐对象至${direction}，基准点: ${value}`);
}

// 分布对象
function distributeObjects(direction: string) {
  if (!canvas.value || !selectedObject.value) return;
  
  console.log(`分布对象: ${direction}`);
  // TODO: 实现分布逻辑
}

// 调整图层
function arrangeLayer(direction: string) {
  if (!canvas.value) return;
  
  const activeObject = canvas.value.getActiveObject();
  if (!activeObject) return;
  
  switch (direction) {
    case 'front':
      activeObject.bringToFront();
      break;
    case 'forward':
      activeObject.bringForward();
      break;
    case 'backward':
      activeObject.sendBackwards();
      break;
    case 'back':
      activeObject.sendToBack();
      break;
  }
  
  canvas.value.renderAll();
}

// 切换锁定状态
function toggleLock() {
  if (!canvas.value || !selectedObject.value) return;
  
  const locked = !selectedObject.value.lockMovementX;
  selectedObject.value.set({
    lockMovementX: locked,
    lockMovementY: locked,
    lockRotation: locked,
    lockScalingX: locked,
    lockScalingY: locked
  });
  
  isLocked.value = locked;
  canvas.value.renderAll();
  
  console.log(`${locked ? '锁定' : '解锁'}对象`);
}

// 切换组合状态
function toggleGroup() {
  if (!canvas.value) return;
  
  const activeObject = canvas.value.getActiveObject();
  
  if (!activeObject) return;
  
  if (activeObject.type === 'group') {
    // 解组
    activeObject.toActiveSelection();
    isGroup.value = false;
  } else if (activeObject.type === 'activeSelection') {
    // 组合
    activeObject.toGroup();
    isGroup.value = true;
  }
  
  canvas.value.renderAll();
  console.log(`${isGroup.value ? '组合' : '解组'}对象`);
}

// 翻转对象
function flipObject(direction: string) {
  if (!canvas.value || !selectedObject.value) return;
  
  if (direction === 'horizontal') {
    selectedObject.value.set('flipX', !selectedObject.value.flipX);
  } else if (direction === 'vertical') {
    selectedObject.value.set('flipY', !selectedObject.value.flipY);
  }
  
  canvas.value.renderAll();
  console.log(`${direction}翻转对象`);
}

// 克隆对象
function cloneObject() {
  if (!canvas.value || !selectedObject.value) return;
  
  selectedObject.value.clone((cloned: any) => {
    cloned.set({
      left: selectedObject.value.left + 20,
      top: selectedObject.value.top + 20
    });
    
    canvas.value.add(cloned);
    canvas.value.setActiveObject(cloned);
    canvas.value.renderAll();
  });
  
  console.log('克隆对象');
}

// 切换网格显示
function toggleGrid() {
  showGrid.value = !showGrid.value;
  
  if (showGrid.value) {
    drawGrid();
  } else {
    clearGrid();
  }
  
  console.log(`${showGrid.value ? '显示' : '隐藏'}网格`);
}

// 绘制网格
function drawGrid() {
  if (!canvas.value) return;
  
  // 清除之前的网格线
  clearGrid();
  
  const gridSize = 20; // 网格大小
  const gridColor = 'rgba(0, 0, 0, 0.15)'; // 增加网格颜色透明度，使其更可见
  const width = workspaceWidth.value;
  const height = workspaceHeight.value;
  
  // 获取工作区位置信息
  const workspace = canvas.value.getObjects().find(
    (obj: any) => obj.id === 'workspace' || obj.name === 'workspace' || obj.name === '工作区'
  );
  
  // 计算偏移量（如果有工作区的话）
  const offsetX = workspace ? workspace.left || 0 : 0;
  const offsetY = workspace ? workspace.top || 0 : 0;
  
  // 创建垂直线
  for (let i = 0; i <= width; i += gridSize) {
    const line = new fabric.Line([i + offsetX, offsetY, i + offsetX, height + offsetY], {
      stroke: gridColor,
      strokeWidth: 0.5,
      selectable: false,
      evented: false,
      excludeFromExport: true,
      name: 'gridLine',
      hoverCursor: 'default'
    });
    gridLines.push(line);
    canvas.value.add(line);
    line.sendToBack();
  }
  
  // 创建水平线
  for (let i = 0; i <= height; i += gridSize) {
    const line = new fabric.Line([offsetX, i + offsetY, width + offsetX, i + offsetY], {
      stroke: gridColor,
      strokeWidth: 0.5,
      selectable: false,
      evented: false,
      excludeFromExport: true,
      name: 'gridLine',
      hoverCursor: 'default'
    });
    gridLines.push(line);
    canvas.value.add(line);
    line.sendToBack();
  }
  
  // 确保工作区在网格之上
  if (workspace) {
    workspace.bringToFront();
  }
  
  canvas.value.renderAll();
}

// 清除网格
function clearGrid() {
  if (!canvas.value) return;
  
  // 移除所有已存在的网格线
  while(gridLines.length > 0) {
    const line = gridLines.pop();
    if (line) {
      canvas.value.remove(line);
    }
  }
  
  // 备用方法：通过name查找并删除
  const existingGridLines = canvas.value.getObjects().filter(
    (obj: any) => obj.name === 'gridLine'
  );
  
  existingGridLines.forEach((line: any) => {
    canvas.value.remove(line);
  });
  
  canvas.value.renderAll();
}

// 切换标尺显示
function toggleRuler() {
  console.log(`切换标尺显示状态，当前值: ${showRuler.value}`);
  
  // 如果已经显示标尺，先清除
  if (showRuler.value) {
    clearRulers();
  }
  
  // 切换状态
  showRuler.value = !showRuler.value;
  
  // 如果切换为显示状态，绘制标尺
  if (showRuler.value) {
    // 延迟一帧绘制标尺，确保DOM更新完成
    nextTick(() => {
      console.log('DOM已更新，开始绘制标尺');
      drawRulers();
      
      // 确保画布被重新渲染
      if (canvas.value) {
        canvas.value.requestRenderAll();
        console.log('画布已重新渲染，确保标尺可见');
      }
    });
  }
  
  console.log(`标尺状态已切换为: ${showRuler.value ? '显示' : '隐藏'}`);
}

// 绘制标尺
function drawRulers() {
  if (!canvas.value) return;
  
  console.log('开始绘制标尺');
  
  // 检查是否真的需要绘制标尺
  if (!showRuler.value) {
    console.log('showRuler为false，取消绘制');
    return;
  }
  
  // 标尺配置
  const rulerHeight = 20;
  const rulerWidth = 20;
  const rulerColor = 'rgba(240,240,240,0.5)'; // 背景透明度50%
  const rulerBorderColor = 'rgba(208,208,208,1)'; // 边框透明度50%
  const rulerTextColor = 'rgba(102,102,102,1)'; // 文字透明度70%，保证可读性
  const rulerFontSize = 10;
  const rulerInterval = 50; // 主刻度间隔
  const minorInterval = 10; // 小刻度间隔
  
  // 标尺偏移量
  const rulerOffsetX = -20; // 偏移
  const rulerOffsetY = -20; // 偏移
  
  const width = workspaceWidth.value;
  const height = workspaceHeight.value;
  
  // 清除之前的标尺 - 在开始绘制前清除，避免重复
  const existingRulers = canvas.value.getObjects().filter(
    (obj: any) => obj.name === 'ruler'
  );
  
  if (existingRulers.length > 0) {
    console.log(`绘制前清除${existingRulers.length}个已存在的标尺元素`);
    existingRulers.forEach((element: any) => {
      canvas.value.remove(element);
    });
  }
  
  // 获取画布视口信息
  const vpt = canvas.value.viewportTransform;
  const zoom = zoomLevel.value;
  
  // 计算画布原点在视口中的位置
  // 获取工作区对象位置（如果存在）
  const workspace = canvas.value.getObjects().find(
    (obj: any) => obj.id === 'workspace' || obj.name === 'workspace' || obj.name === '工作区'
  );
  
  // 计算偏移量，确保标尺与画布边缘对齐
  const translateX = workspace ? workspace.left || 0 : 0;
  const translateY = workspace ? workspace.top || 0 : 0;
  
  // 水平标尺背景
  const horizontalRuler = new fabric.Rect({
    left: rulerOffsetX,
    top: rulerOffsetY,
    width: width + rulerWidth,
    height: rulerHeight,
    fill: rulerColor,
    stroke: rulerBorderColor,
    strokeWidth: 1,
    selectable: false,
    evented: false,
    excludeFromExport: true,
    name: 'ruler',
    opacity: 1, // 确保不透明
    visible: true // 确保可见
  });
  
  // 垂直标尺背景
  const verticalRuler = new fabric.Rect({
    left: rulerOffsetX,
    top: rulerOffsetY,
    width: rulerWidth,
    height: height + rulerHeight,
    fill: rulerColor,
    stroke: rulerBorderColor,
    strokeWidth: 1,
    selectable: false,
    evented: false,
    excludeFromExport: true,
    name: 'ruler',
    opacity: 1, // 确保不透明
    visible: true // 确保可见
  });
  
  // 添加标尺背景
  canvas.value.add(horizontalRuler);
  canvas.value.add(verticalRuler);
  
  // 创建水平标尺刻度 - 起点对齐工作区左边缘
  for (let i = 0; i <= width; i += minorInterval) {
    let markHeight = rulerHeight / 4;
    let strokeWidth = 1;
    
    if (i % rulerInterval === 0) {
      markHeight = rulerHeight / 2;
      strokeWidth = 1.5;
      
      // 添加文字，从0开始标记实际距离
      const text = new fabric.Text(i.toString(), {
        left: i + rulerWidth - translateX + rulerOffsetX,
        top: 5 + rulerOffsetY,
        fontSize: rulerFontSize,
        fill: rulerTextColor,
        selectable: false,
        evented: false,
        excludeFromExport: true,
        name: 'ruler'
      });
      
      canvas.value.add(text);
    }
    
    const mark = new fabric.Line(
      [i + rulerWidth - translateX + rulerOffsetX, rulerHeight - markHeight + rulerOffsetY, i + rulerWidth - translateX + rulerOffsetX, rulerHeight + rulerOffsetY],
      {
        stroke: rulerBorderColor,
        strokeWidth: strokeWidth,
        selectable: false,
        evented: false,
        excludeFromExport: true,
        name: 'ruler'
      }
    );
    
    canvas.value.add(mark);
  }
  
  // 创建垂直标尺刻度 - 起点对齐工作区上边缘
  for (let i = 0; i <= height; i += minorInterval) {
    let markWidth = rulerWidth / 4;
    let strokeWidth = 1;
    
    if (i % rulerInterval === 0) {
      markWidth = rulerWidth / 2;
      strokeWidth = 1.5;
      
      // 添加文字，从0开始标记实际距离
      const text = new fabric.Text(i.toString(), {
        left: 2 + rulerOffsetX,
        top: i + rulerHeight - translateY + rulerOffsetY,
        fontSize: rulerFontSize,
        fill: rulerTextColor,
        selectable: false,
        evented: false,
        excludeFromExport: true,
        name: 'ruler'
      });
      
      canvas.value.add(text);
    }
    
    const mark = new fabric.Line(
      [rulerWidth - markWidth + rulerOffsetX, i + rulerHeight - translateY + rulerOffsetY, rulerWidth + rulerOffsetX, i + rulerHeight - translateY + rulerOffsetY],
      {
        stroke: rulerBorderColor,
        strokeWidth: strokeWidth,
        selectable: false,
        evented: false,
        excludeFromExport: true,
        name: 'ruler'
      }
    );
    
    canvas.value.add(mark);
  }
  
  // 标尺角落
  const rulerCorner = new fabric.Rect({
    left: rulerOffsetX,
    top: rulerOffsetY,
    width: rulerWidth,
    height: rulerHeight,
    fill: rulerColor,
    stroke: rulerBorderColor,
    strokeWidth: 1,
    selectable: false,
    evented: false,
    excludeFromExport: true,
    name: 'ruler',
    opacity: 1,
    visible: true
  });
  
  // 在角落添加原点标记 - 确保原点位于正确位置
  const originMark = new fabric.Circle({
    left: rulerWidth - 4 + rulerOffsetX,
    top: rulerHeight - 4 + rulerOffsetY,
    radius: 4,
    fill: 'rgba(24, 144, 255, 0.7)',
    stroke: 'rgba(24, 144, 255, 0.9)',
    strokeWidth: 1,
    selectable: false,
    evented: false,
    excludeFromExport: true,
    name: 'ruler',
    opacity: 1,
    visible: true
  });
  
  canvas.value.add(rulerCorner);
  canvas.value.add(originMark);
  canvas.value.renderAll();
  
  console.log('标尺绘制完成');
}

// 清除标尺
function clearRulers() {
  if (!canvas.value) return;
  
  console.log('清除标尺元素');
  
  // 获取所有标尺元素并移除
  const rulerElements = canvas.value.getObjects().filter(
    (obj: any) => obj.name === 'ruler'
  );
  
  if (rulerElements.length > 0) {
    rulerElements.forEach((element: any) => {
      canvas.value.remove(element);
    });
    
    // 确保渲染更新
    canvas.value.renderAll();
    console.log(`已移除 ${rulerElements.length} 个标尺元素`);
  } else {
    console.log('没有找到标尺元素需要清除');
  }
}

// 显示参考线
function toggleGuidelines() {
  if (!canvas.value) return;
  
  // 切换参考线显示状态
  showGuides.value = !showGuides.value;
  
  if (showGuides.value) {
    // 添加参考线
    const width = workspaceWidth.value;
    const height = workspaceHeight.value;
    
    // 添加水平居中参考线
    addGuide('horizontal', height / 2);
    
    // 添加垂直居中参考线
    addGuide('vertical', width / 2);
    
    console.log('显示参考线');
  } else {
    // 清除参考线
    clearGuidelines();
    console.log('隐藏参考线');
  }
}

// 清除参考线
function clearGuidelines() {
  if (!canvas.value) return;
  
  // 获取所有参考线并移除
  const guidelines = canvas.value.getObjects().filter(
    (obj: any) => obj.name === 'guideline'
  );
  
  guidelines.forEach((guideline: any) => {
    canvas.value.remove(guideline);
  });
  
  canvas.value.renderAll();
  console.log(`已移除 ${guidelines.length} 条参考线`);
}

// 添加参考线
function addGuide(orientation: 'horizontal' | 'vertical', position: number) {
  if (!canvas.value) return;
  
  const width = workspaceWidth.value;
  const height = workspaceHeight.value;
  const guideColor = '#00a8ff';
  
  let guide;
  
  if (orientation === 'horizontal') {
    guide = new fabric.Line([0, position, width, position], {
      stroke: guideColor,
      strokeWidth: 1,
      strokeDashArray: [5, 5],
      selectable: true,
      lockMovementX: true,
      excludeFromExport: true,
      hasControls: false,
      hasBorders: false,
      name: 'guideline'
    });
  } else {
    guide = new fabric.Line([position, 0, position, height], {
      stroke: guideColor,
      strokeWidth: 1,
      strokeDashArray: [5, 5],
      selectable: true,
      lockMovementY: true,
      excludeFromExport: true,
      hasControls: false,
      hasBorders: false,
      name: 'guideline'
    });
  }
  
  canvas.value.add(guide);
  canvas.value.renderAll();
}

// 显示尺寸
function showDimensions() {
  if (!canvas.value || !selectedObject.value) return;
  
  const obj = selectedObject.value;
  const width = Math.round(obj.getScaledWidth());
  const height = Math.round(obj.getScaledHeight());
  const left = Math.round(obj.left);
  const top = Math.round(obj.top);
  
  // 创建显示尺寸的文本
  const dimensionText = new fabric.Text(`${width} × ${height}`, {
    left: left + width / 2,
    top: top - 20,
    fontSize: 12,
    fill: '#333',
    backgroundColor: 'rgba(255,255,255,0.7)',
    textAlign: 'center',
    originX: 'center',
    selectable: false,
    evented: false,
    name: 'dimension'
  });
  
  // 创建位置标签
  const positionText = new fabric.Text(`(${left}, ${top})`, {
    left: left - 10,
    top: top - 10,
    fontSize: 12,
    fill: '#333',
    backgroundColor: 'rgba(255,255,255,0.7)',
    selectable: false,
    evented: false,
    name: 'dimension'
  });
  
  // 移除之前的尺寸标签
  clearDimensions();
  
  // 添加新的尺寸标签
  canvas.value.add(dimensionText);
  canvas.value.add(positionText);
  canvas.value.renderAll();
  
  // 设置定时器在几秒后自动移除尺寸标签
  setTimeout(() => {
    clearDimensions();
  }, 3000);
  
  console.log('显示尺寸');
}

// 清除尺寸标签
function clearDimensions() {
  if (!canvas.value) return;
  
  // 获取所有尺寸标签并移除
  const dimensions = canvas.value.getObjects().filter(
    (obj: any) => obj.name === 'dimension'
  );
  
  dimensions.forEach((dim: any) => {
    canvas.value.remove(dim);
  });
  
  canvas.value.renderAll();
}

// 处理对象选中事件 - 更新 textSettings 以同步左侧面板
function handleObjectSelected(e: any) {
  if (!canvas.value) return;
  
  // 获取选中对象
  const activeObject = canvas.value.getActiveObject();
  
  if (activeObject) {
    console.log('对象已选中:', activeObject.type);
    
    // 更新选中对象状态
    selectedObject.value = activeObject;
    
    // 更新锁定状态
    isLocked.value = activeObject.lockMovementX && 
                      activeObject.lockMovementY && 
                      activeObject.lockRotation && 
                      activeObject.lockScalingX && 
                      activeObject.lockScalingY;
    
    // 更新组状态
    isGroup.value = activeObject.type === 'group';
  }
}

// 同步左侧文字面板的状态 (当右侧属性面板修改或选中对象时调用)
function syncLeftTextPanel(target: any | null = selectedObject.value) {
  if (target && target.type === 'i-text') {
     textSettings.fontFamily = target.fontFamily || 'Arial';
     textSettings.fontSize = target.fontSize || 24;
     textSettings.color = target.fill || '#333333';
  }
}

// 当右侧字体选择变化时，同步左侧
function syncFontFamily() {
  if (selectedObject.value && selectedObject.value.type === 'i-text') {
     textSettings.fontFamily = selectedObject.value.fontFamily;
  }
}

// 当右侧字号变化时，同步左侧
function syncFontSize() {
  if (selectedObject.value && selectedObject.value.type === 'i-text') {
     textSettings.fontSize = selectedObject.value.fontSize;
  }
}

// 切换文字样式 (粗体、斜体、下划线)
function toggleTextStyle(prop: string, activeValue: any, inactiveValue: any) {
  if (!selectedObject.value || selectedObject.value.type !== 'i-text') return;
  
  const currentValue = selectedObject.value.get(prop);
  selectedObject.value.set(prop, currentValue === activeValue ? inactiveValue : activeValue);
  requestRender();
}

// 设置文本对齐 (这个函数之前没有被用到，如果需要对齐功能可以取消注释)
/*
function setTextAlign(align: string) {
  if (!selectedObject.value || selectedObject.value.type !== 'i-text') return;
  
  selectedObject.value.set('textAlign', align);
  requestRender();
}
*/

// 处理取消选择事件
function handleSelectionCleared() {
  selectedObject.value = null;
  isLocked.value = false;
  isGroup.value = false;
}


// // 添加变量
// const textSettings = reactive({
//   fontFamily: 'Arial',
//   fontSize: 24,
//   color: '#333333'
// });

// const previewDevice = ref('desktop');

// const exportSettings = reactive({
//   format: 'png',
//   quality: 90,
//   width: workspaceWidth.value,
//   height: workspaceHeight.value,
//   maintainRatio: true
// });

// // 添加新文本
// function addNewText(type: string) {
//   console.log(`尝试添加文本: ${type}，当前画布实例:`, canvas.value);
//   if (!canvas.value) {
//     console.error('错误：无法添加文本，因为 canvas.value 无效！');
//         return;
//       }

//   let text = '';
//   let fontSize = 14;
//   let fontWeight = 'normal';
  
//   switch (type) {
//     case 'heading':
//       text = '标题文本';
//       fontSize = 32;
//       fontWeight = 'bold';
//       break;
//     case 'subheading':
//       text = '副标题文本';
//       fontSize = 24;
//       break;
//     case 'paragraph':
//       text = '段落文本';
//       fontSize = 16;
//       break;
//   }
  
//   try {
//     console.log('准备创建 fabric.IText 对象...');
//     const textObj = new fabric.IText(text, {
//       left: workspaceWidth.value / 2,
//       top: workspaceHeight.value / 2,
//       fontSize,
//       fontFamily: textSettings.fontFamily,
//       fill: textSettings.color,
//       fontWeight,
//       originX: 'center',
//       originY: 'center'
//     });
//     console.log('fabric.IText 对象已创建:', textObj);
    
//     console.log('准备将文本对象添加到画布...');
//     canvas.value.add(textObj);
//     console.log('文本对象已添加到画布');
    
//     console.log('准备设置活动对象...');
//     canvas.value.setActiveObject(textObj);
//     console.log('活动对象已设置');
    
//     console.log('准备渲染画布...');
//     canvas.value.renderAll();
//     console.log('画布已渲染');
    
//     console.log(`成功添加 ${type} 文本`);
//   } catch (err) {
//     console.error(`添加 ${type} 文本时出错:`, err);
//   }
// }

// // 文本字号调整
// function increaseFontSize() {
//   textSettings.fontSize += 2;
//   updateSelectedTextStyle();
// }

// function decreaseFontSize() {
//   if (textSettings.fontSize > 8) {
//     textSettings.fontSize -= 2;
//     updateSelectedTextStyle();
//   }
// }

// function updateSelectedTextStyle() {
//   if (!canvas.value || !selectedObject.value || selectedObject.value.type !== 'i-text') return;
  
//   selectedObject.value.set({
//     fontFamily: textSettings.fontFamily,
//     fontSize: textSettings.fontSize,
//     fill: textSettings.color
//   });
  
//   canvas.value.renderAll();
// }

// 添加三角形
function addNewTriangle() {
  console.log('尝试添加三角形，当前画布实例:', canvas.value); // 在添加前打印 canvas.value
  if (!canvas.value) {
    console.error('错误：无法添加三角形，因为 canvas.value 无效！');
        return;
      }
      
      // 获取下一个元素位置
      const position = getNextElementPosition();
      
      const triangle = new fabric.Triangle({
    left: position.left,
    top: position.top,
        width: 100,
        height: 100,
    fill: '#ffc107',
    stroke: '#d39e00',
    strokeWidth: 1,
    originX: 'left',
    originY: 'top',
    name: '三角形'
      });
      
  canvas.value.add(triangle);
  canvas.value.setActiveObject(triangle);
  canvas.value.renderAll();
  console.log(`添加三角形，位置(${position.left}, ${position.top})`);
}

// 添加直线
function addNewLine() {
  console.log('尝试添加直线，当前画布实例:', canvas.value); // 在添加前打印 canvas.value
  if (!canvas.value) {
    console.error('错误：无法添加直线，因为 canvas.value 无效！');
        return;
      }
      
      // 获取下一个元素位置
      const position = getNextElementPosition();
      
      const line = new fabric.Line([
    position.left, position.top, 
    position.left + 100, position.top
  ], {
    stroke: '#6c757d',
    strokeWidth: 2,
    originX: 'left',
    originY: 'top',
    name: '直线'
  });
  
  canvas.value.add(line);
  canvas.value.setActiveObject(line);
  canvas.value.renderAll();
  console.log(`添加直线，位置(${position.left}, ${position.top})`);
}
    
    // 预览与导出
function openPreview() {
  console.log('在新窗口预览');
  // TODO: 实现预览功能
}

async function exportDesign() { // 改为 async 函数以方便处理克隆
  console.log('Export button clicked. Checking canvas...', canvas.value);
  if (!canvas.value) {
    console.error('无法导出：画布实例无效！');
    return;
  }

  const workspaceObj = canvas.value.getObjects().find((obj: any) => obj.type === 'rect'); // 假设工作区是第一个 Rect
  if (!workspaceObj) {
      console.error('无法导出：找不到工作区对象！');
      return;
  }
  console.log('Found workspace object:', workspaceObj);
  
  const format = exportSettings.format || 'png';
  const quality = (exportSettings.quality || 90) / 100; 
  let exportWidth = exportSettings.width || workspaceObj.width; 
  let exportHeight = exportSettings.height || workspaceObj.height;

  // ... (保持比例计算不变) ...
  if (exportSettings.maintainRatio && workspaceObj.width > 0 && workspaceObj.height > 0) {
    const originalRatio = workspaceObj.width / workspaceObj.height;
    let tempHeight = exportWidth / originalRatio;
    if (tempHeight > exportHeight) { 
        exportWidth = exportHeight * originalRatio;
    } else {
        exportHeight = tempHeight;
    }
     exportWidth = Math.round(exportWidth);
     exportHeight = Math.round(exportHeight);
  }
  
  console.log(`Target export size: ${exportWidth}x${exportHeight}, Format: ${format}`);

  try {
    // 直接创建一个简单的 canvas 元素，不使用 fabric
    console.log('Creating a simple canvas for export...');
    const tempCanvasElement = document.createElement('canvas');
    tempCanvasElement.width = exportWidth;
    tempCanvasElement.height = exportHeight;
    const tempCtx = tempCanvasElement.getContext('2d');
    
    if (!tempCtx) {
      console.error('无法获取 canvas 2D 上下文');
      return;
    }
    
    // 设置白色背景
    tempCtx.fillStyle = 'white';
    tempCtx.fillRect(0, 0, exportWidth, exportHeight);
    
    // 获取主画布的 URL 数据，排除了工作区外的内容
    if (canvas.value) {
      console.log('获取主画布的缩略图...');
      // 保存原始状态以便还原
      const originalZoom = canvas.value.getZoom();
      const originalViewportTransform = [...canvas.value.viewportTransform];
      
      try {
        // 计算工作区位置和尺寸相对于主画布的比例
        const workspaceLeft = workspaceObj.left || 0;
        const workspaceTop = workspaceObj.top || 0;
        const workspaceWidth = workspaceObj.width || exportWidth;
        const workspaceHeight = workspaceObj.height || exportHeight;
        
        console.log(`工作区位置: 左=${workspaceLeft}, 上=${workspaceTop}, 宽=${workspaceWidth}, 高=${workspaceHeight}`);
        
        // 临时将缩放设置为 1，确保获取原始大小的对象
        canvas.value.setZoom(1);
        
        // 临时隐藏工作区矩形，使其不会出现在导出的图像中
        const wasWorkspaceVisible = workspaceObj.visible;
        workspaceObj.visible = false;
        
        // 调整视口变换，聚焦于工作区
        canvas.value.setViewportTransform([1, 0, 0, 1, -workspaceLeft, -workspaceTop]);
        
        // 让 fabric 重新渲染以应用更改
        canvas.value.renderAll();
        
        // 导出图像
        const dataURL = canvas.value.toDataURL({
          format: format === 'jpg' ? 'jpeg' : 'png',
          quality: quality,
          left: 0,
          top: 0,
          width: workspaceWidth,
          height: workspaceHeight
        });
        
        console.log(`生成的 dataURL 长度: ${dataURL.length}`);
        
        // 将 dataURL 绘制到简单 canvas 上
        const img = new Image();
        img.onload = function() {
          tempCtx.drawImage(img, 0, 0, exportWidth, exportHeight);
          
          // 从简单 canvas 获取最终的 dataURL
          const finalDataURL = tempCanvasElement.toDataURL(
            format === 'jpg' ? 'image/jpeg' : 'image/png',
            quality
          );
        
        // 创建下载链接
        const link = document.createElement('a');
          link.download = `design.${format}`;
          link.href = finalDataURL;
        document.body.appendChild(link);
          console.log('触发下载...');
        link.click();
        document.body.removeChild(link);
          console.log('下载链接已处理。');
        };
        img.onerror = function(err) {
          console.error('图片加载错误:', err);
        };
        img.src = dataURL;
        
        // 恢复原始状态
        workspaceObj.visible = wasWorkspaceVisible;
        canvas.value.setZoom(originalZoom);
        canvas.value.setViewportTransform(originalViewportTransform);
        canvas.value.renderAll();
        
      } catch (err) {
        console.error('导出过程中出错:', err);
        
        // 恢复原始状态
        canvas.value.setZoom(originalZoom);
        canvas.value.setViewportTransform(originalViewportTransform);
        canvas.value.renderAll();
      }
    }
  } catch (err) {
    console.error('导出过程中发生异常:', err);
  }
  
  console.log(`导出设计为 ${format}, 请求尺寸: ${exportSettings.width}x${exportSettings.height}, 实际导出尺寸: ${exportWidth}x${exportHeight}, 质量: ${exportSettings.quality}%`);
}

// 新增一个简单的渲染请求函数，用于 @change 或 @input
function requestRender() {
  if (canvas.value) {
    console.log('请求渲染画布');
    canvas.value.renderAll();
  }
}

// 格式化文本
function formatText(formatType: string) {
  if (!canvas.value || !selectedObject.value) return;
  
  if (selectedObject.value.type !== 'i-text' && selectedObject.value.type !== 'textbox') {
    console.log('没有选中文本对象');
    return;
  }
  
  switch (formatType) {
    case 'bold':
      const currentWeight = selectedObject.value.fontWeight;
      selectedObject.value.set('fontWeight', currentWeight === 'bold' ? 'normal' : 'bold');
      break;
    case 'italic':
      const currentStyle = selectedObject.value.fontStyle;
      selectedObject.value.set('fontStyle', currentStyle === 'italic' ? 'normal' : 'italic');
      break;
    case 'underline':
      const currentUnderline = selectedObject.value.underline;
      selectedObject.value.set('underline', !currentUnderline);
      break;
    case 'alignLeft':
      selectedObject.value.set('textAlign', 'left');
      break;
    case 'alignCenter':
      selectedObject.value.set('textAlign', 'center');
      break;
    case 'alignRight':
      selectedObject.value.set('textAlign', 'right');
      break;
  }
  
  canvas.value.renderAll();
  console.log(`文本格式更新: ${formatType}`);
}

// 添加多边形
function addNewPolygon() {
  console.log('尝试添加多边形，当前画布实例:', canvas.value); // 在添加前打印 canvas.value
  if (!canvas.value) {
    console.error('错误：无法添加多边形，因为 canvas.value 无效！');
        return;
      }
      
      // 获取下一个元素位置
      const position = getNextElementPosition();
      
      const polygon = new fabric.Polygon([
    { x: 0, y: -50 },
    { x: 50, y: -50 },
    { x: 75, y: 0 },
    { x: 50, y: 50 },
    { x: 0, y: 50 },
    { x: -25, y: 0 }
  ], {
    left: position.left,
    top: position.top,
    fill: '#9932cc',
    stroke: '#732699',
    strokeWidth: 1,
    originX: 'left',
    originY: 'top',
    name: '多边形'
  });
  
  canvas.value.add(polygon);
  canvas.value.setActiveObject(polygon);
  canvas.value.renderAll();
  console.log(`添加多边形，位置(${position.left}, ${position.top})`);
}

// 添加素材到画布
function addMaterialToCanvas(id: string) {
  if (!canvas.value) {
    console.error('无法添加素材：画布实例不存在');
    return;
  }
  
  console.log(`添加素材: ${id}`);
  
  // 根据ID添加不同的素材
  // 这里只是一个示例实现
  const material = new fabric.Rect({
    width: 100,
    height: 100,
    fill: '#' + Math.floor(Math.random()*16777215).toString(16),
    left: workspaceWidth.value / 2,
    top: workspaceHeight.value / 2,
    originX: 'center',
    originY: 'center'
  });
  
  canvas.value.add(material);
  canvas.value.setActiveObject(material);
  canvas.value.renderAll();
}

// 应用背景颜色 (新函数，处理来自子组件的事件)
function applyBackgroundColorInternal(color: string) {
  if (!canvas.value) {
    console.error('无法应用背景颜色：画布实例不存在');
    return;
  }
  
  const workspace = canvas.value.getObjects().find((obj: fabric.Object) => obj.id === 'workspace') as fabric.Rect;
  if (workspace) {
    workspace.set('fill', color);
    canvas.value.renderAll();
    console.log(`应用背景颜色: ${color}`);
  } else {
    console.error('无法找到工作区对象');
  }
}

// 修复选择比例函数
// 已移至 TemplatePanel
function selectRatio(ratio: string) {
  if (!canvas.value) {
    console.error('无法应用比例：画布实例不存在');
    return;
  }
  
  const gradConfig = {
    coords: { x1: 0, y1: 0, x2: workspaceWidth.value, y2: 0 } as { x1: number; y1: number; x2: number; y2: number }
  };

  try {
    console.log('SimpleEditorView: 根据比例创建渐变背景:', ratio);
    const gradient = new fabric.Gradient({
      colorStops: [
        { offset: 0, color: '#1890ff' },
        { offset: 1, color: '#f759ab' }
      ],
      coords: gradConfig.coords
    });
    
    canvas.value.setBackgroundColor(gradient, () => {
      canvas.value.renderAll();
      console.log('SimpleEditorView: 渐变背景已应用');
    });
  } catch (err) {
     console.error('SimpleEditorView: 创建或应用渐变背景时出错:', err);
  }
}

// 预留背景图片处理函数
function handleBackgroundImageChange(payload: { file: File, options: { repeat: boolean, stretch: boolean } }) {
   console.log('SimpleEditorView: Received background-image-change event:', payload);
   // TODO: 实现背景图片逻辑
}

// 处理TextPanel组件的样式更新事件
function handleTextStyleUpdate(payload: { property: string, value: string | number }) {
  console.log('接收到文本样式更新:', payload);
  if (!selectedObject.value || !canvas.value) return;
  
  // 更新文本设置状态
  if (payload.property === 'fontFamily') {
    textSettings.fontFamily = payload.value as string;
  } else if (payload.property === 'fontSize') {
    textSettings.fontSize = payload.value as number;
  } else if (payload.property === 'color') {
    textSettings.color = payload.value as string;
  }
  
  // 应用到选中的文本对象
  if (selectedObject.value.type === 'textbox' || selectedObject.value.type === 'i-text') {
    selectedObject.value.set(payload.property, payload.value);
    canvas.value.renderAll();
  }
}

// 用于预览面板的设备尺寸计算
const deviceDimensions = computed(() => {
  if (previewDevice.value === 'desktop') {
    return '1920 × 1080';
  } else if (previewDevice.value === 'tablet') {
    return '768 × 1024';
  } else if (previewDevice.value === 'mobile') {
    return '375 × 667';
  }
  return `${workspaceWidth.value} × ${workspaceHeight.value}`;
});

// 处理导出尺寸变更
function handleExportDimensionChange(dimension: string, value: number) {
  if (dimension === 'width') {
    exportSettings.width = value;
    if (exportSettings.maintainRatio && workspaceWidth.value && workspaceHeight.value) {
      const ratio = workspaceHeight.value / workspaceWidth.value;
      exportSettings.height = Math.round(value * ratio);
    }
  } else if (dimension === 'height') {
    exportSettings.height = value;
    if (exportSettings.maintainRatio && workspaceWidth.value && workspaceHeight.value) {
      const ratio = workspaceWidth.value / workspaceHeight.value;
      exportSettings.width = Math.round(value * ratio);
    }
  }
}

// 添加元素计数器和偏移量管理
const elementCounter = ref(0);

// 获取下一个元素位置
function getNextElementPosition() {
  // 递增计数器
  elementCounter.value++;
  
  // 计算新位置
  const offsetX = 100 + (elementCounter.value - 1) * 5;
  const offsetY = 100 + (elementCounter.value - 1) * 5;
  
  return { left: offsetX, top: offsetY };
}

// 添加文本
function addNewText(type: string) {
  if (!canvas.value) return;
  
  let text = '双击编辑文本';
  let fontSize = 24;
  let fontWeight = 'normal';
  let fontStyle = 'normal';
  let textAlign = 'center';
  
  // 根据类型设置不同的文本参数
  switch (type) {
    case 'heading':
      text = '标题文本';
      fontSize = 32;
      fontWeight = 'bold';
      break;
    case 'subheading':
      text = '副标题文本';
      fontSize = 24;
      break;
    case 'paragraph':
      text = '这是一段文字段落，您可以双击编辑内容...';
      fontSize = 16;
      textAlign = 'left';
      break;
    default:
      text = '双击编辑文本';
  }
  
  // 获取下一个元素位置
  const position = getNextElementPosition();
  
  const textObj = new fabric.IText(text, {
    left: position.left,
    top: position.top,
    fontSize: fontSize,
    fontFamily: textSettings.fontFamily,
    fill: textSettings.color,
    fontWeight: fontWeight,
    fontStyle: fontStyle,
    textAlign: textAlign,
    originX: 'left',
    originY: 'top',
    name: type === 'heading' ? '标题' : (type === 'subheading' ? '副标题' : '段落文本')
  });
  
  canvas.value.add(textObj);
  canvas.value.setActiveObject(textObj);
  canvas.value.renderAll();
  console.log(`添加${type}文本，位置(${position.left}, ${position.top})`);
  
  // 更新图层列表
  updateLayersList();
}

// 添加渐变文字
function addGradientText() {
  if (!canvas.value) return;
  
  // 创建渐变对象
  const gradient = new fabric.Gradient({
    type: 'linear',
    coords: { x1: 0, y1: 0, x2: 1, y2: 0 },
    colorStops: [
      { offset: 0, color: '#f3ec78' },
      { offset: 1, color: '#af4261' }
    ]
  });
  
  // 获取下一个元素位置
  const position = getNextElementPosition();
  
  // 创建文本对象
  const text = new fabric.IText('渐变文字', {
    left: position.left,
    top: position.top,
    fontSize: 32,
    fontFamily: textSettings.fontFamily,
    fontWeight: 'bold',
    fill: gradient,
    originX: 'left',
    originY: 'top',
    name: '渐变文字'
  });
  
  canvas.value.add(text);
  canvas.value.setActiveObject(text);
  canvas.value.renderAll();
  console.log(`添加渐变文字，位置(${position.left}, ${position.top})`);
  
  // 更新图层列表
  updateLayersList();
}

// 处理 TemplatePanel 发出的尺寸更新事件
function handleCanvasResize({ width, height }: { width: number, height: number }) {
  console.log(`接收到尺寸更新事件: ${width}x${height}`);
  
  // 更新相关状态变量
  workspaceWidth.value = width;
  workspaceHeight.value = height;
  exportSettings.width = width;
  exportSettings.height = height;
  
  // 确保画布实例和编辑器引用存在
  if (!canvas.value || !fabricEditorRef.value) {
    console.error('画布实例或编辑器引用不存在，无法更新画布尺寸');
    return;
  }
  
  // 触发布局更新和画布重建
  try {
    console.log(`准备创建${width}x${height}的空白画布...`);
    
    // 重要：先调用setCanvasSize设置画布尺寸
    fabricEditorRef.value.setCanvasSize(width, height);
    
    // 允许UI更新
    nextTick(() => {
      console.log('画布尺寸更新完成，UI已更新');
    });
  } catch (err) {
    console.error('更新画布尺寸时出错:', err);
  }
}

// 其他函数...

// 处理MaterialPanel组件的添加形状事件
function handleAddShape(shapeType: string) {
  console.log('处理添加形状事件:', shapeType);
  
  if (!canvas.value) {
    console.error('无法添加形状：画布实例不存在');
    return;
  }
  
  switch (shapeType) {
    case 'rect':
      addNewRect();
      break;
    case 'circle':
      addNewCircle();
      break;
    case 'triangle':
      addNewTriangle();
      break;
    case 'polygon':
      addNewPolygon();
      break;
    case 'line':
      addNewLine();
      break;
    default:
      console.warn(`未知的形状类型: ${shapeType}`);
  }
}

// 处理MaterialPanel组件的添加材料事件
function handleAddMaterial(materialId: string) {
  console.log('处理添加材料事件:', materialId);
  
  if (!canvas.value) {
    console.error('无法添加材料：画布实例不存在');
    return;
  }
  
  // 获取下一个元素位置
  const position = getNextElementPosition();
  
  // 创建一个简单的素材（实际应用中应该根据materialId从素材库获取）
  const material = {
    width: 100,
    height: 100,
    fill: '#' + Math.floor(Math.random()*16777215).toString(16), // 随机颜色
    left: position.left,
    top: position.top,
    originX: 'left',
    originY: 'top',
    name: `素材${materialId}`
  };
  
  // 添加素材到画布
  const shape = new fabric.Rect(material);
  canvas.value.add(shape);
  canvas.value.setActiveObject(shape);
  canvas.value.renderAll();
  
  console.log(`添加素材，位置(${position.left}, ${position.top})`);
  
  // 更新图层列表
  updateLayersList();
}

// 处理上传图片
function handleUploadImage(dataUrl: string) {
  console.log('处理上传图片:', dataUrl);
  
  if (!canvas.value) {
    console.error('无法添加图片：画布实例不存在');
    return;
  }
  
  // 获取下一个元素位置
  const position = getNextElementPosition();
  
  // 使用dataUrl创建图片对象并添加到画布
  fabric.Image.fromURL(dataUrl, (img: fabric.Image) => {
    // 设置图片属性
    img.set({
      left: position.left,
      top: position.top,
      originX: 'left',
      originY: 'top',
      name: '上传图片'
    });
    
    // 调整图片大小以适应画布
    const maxWidth = workspaceWidth.value * 0.8;
    const maxHeight = workspaceHeight.value * 0.8;
    
    if (img.width && img.height) {
      if (img.width > maxWidth || img.height > maxHeight) {
        const scale = Math.min(maxWidth / img.width, maxHeight / img.height);
        img.scale(scale);
      }
    }
    
    // 添加到画布
    canvas.value.add(img);
    canvas.value.setActiveObject(img);
    canvas.value.renderAll();
    
    console.log(`添加上传图片，位置(${position.left}, ${position.top})`);
    
    // 更新图层列表
    updateLayersList();
  });
}

// 重置元素计数器 - 当清空画布或创建新画布时调用
function resetElementCounter() {
  elementCounter.value = 0;
}



// 处理应用背景色
function handleApplyBackground(color: string) {
  console.log('应用背景颜色:', color);
  
  if (!canvas.value) {
    console.error('无法应用背景：画布实例不存在');
    return;
  }
  
  // 设置画布背景颜色
  canvas.value.setBackgroundColor(color, () => {
    canvas.value.renderAll();
    console.log('背景颜色已应用');
  });
}

// 处理背景渐变
function handleBackgroundGradientChange(payload: { startColor: string; endColor: string; direction: string }) {
  console.log('应用背景渐变:', payload);
  
  if (!canvas.value) {
    console.error('无法应用背景渐变：画布实例不存在');
    return;
  }
  
  const { startColor, endColor, direction } = payload;
  
  // 创建渐变选项
  const gradOpts = {
    colorStops: [
      { offset: 0, color: startColor },
      { offset: 1, color: endColor }
    ],
    coords: { x1: 0, y1: 0, x2: 0, y2: 0 } as { x1: number; y1: number; x2: number; y2: number }
  };
  
  // 根据方向设置渐变坐标
  switch (direction) {
    case 'linear-to-right':
      gradOpts.coords = { x1: 0, y1: 0, x2: workspaceWidth.value, y2: 0 };
      break;
    case 'linear-to-bottom':
      gradOpts.coords = { x1: 0, y1: 0, x2: 0, y2: workspaceHeight.value };
      break;
    case 'radial':
      // 径向渐变需要不同的处理，这里简化处理
      gradOpts.coords = { x1: 0, y1: 0, x2: 0, y2: 0 };
      break;
    default:
      gradOpts.coords = { x1: 0, y1: 0, x2: workspaceWidth.value, y2: 0 };
  }
  
  // 创建并应用渐变
  try {
    const gradient = new fabric.Gradient(gradOpts);
    
    canvas.value.setBackgroundColor(gradient, () => {
      canvas.value.renderAll();
      console.log('背景渐变已应用');
    });
  } catch (err) {
    console.error('应用背景渐变时出错:', err);
  }
}

// 修复其他隐式any类型
function setWorkspaceColor(color: string) {
  if (!canvas.value) {
    console.error('无法设置工作区颜色: 画布不存在');
    return;
  }
  
  const workspace = canvas.value.getObjects().find((obj: fabric.Object) => obj.id === 'workspace') as fabric.Rect;
  if (workspace) {
    workspace.set('fill', color);
    canvas.value.renderAll();
    console.log('工作区颜色已设置为', color);
  }
}

// 在预设模板中修复渐变参数错误
function handlePresetRatioChange(ratio: string) {
  console.log('预设比例更改为:', ratio);
  
  if (!canvas.value) {
    console.error('无法应用预设比例：画布实例不存在');
    return;
  }
  
  // 这里应该使用局部变量，而不是引用不存在的gradientOptions
  const newWidth = 800;
  const gradConfig = {
    coords: { x1: 0, y1: 0, x2: newWidth, y2: 0 } as { x1: number; y1: number; x2: number; y2: number }
  };
  
  switch (ratio) {
    case '16:9':
      // 使用上面定义的局部变量
      console.log('应用16:9比例配置');
      break;
  }
  
  try {
    console.log('SimpleEditorView: Creating gradient with options:', gradConfig); // 使用局部变量
    const gradient = new fabric.Gradient({
      colorStops: [
        { offset: 0, color: '#1890ff' },
        { offset: 1, color: '#f759ab' }
      ],
      coords: gradConfig.coords
    });
    
    console.log('SimpleEditorView: Gradient object created:', gradient);
    
    canvas.value.setBackgroundColor(gradient, () => {
      canvas.value.renderAll();
      console.log('Gradient background applied');
    });
  } catch (err) {
    console.error('Error applying gradient background:', err);
  }
}

// 处理缩放变化
function handleZoomChanged(zoom: number) {
  zoomLevel.value = zoom;
}

</script>

<style scoped>
.design-editor-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.editor-main {
  display: flex;
  flex: 1;
  height: calc(100vh - 60px);
  overflow: hidden;
}

/* 侧边栏样式 */
.editor-sidebar {
  width: 250px;
  background-color: #f8f9fa;
  border-right: 1px solid #e0e0e0;
  height: 100%;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
}

.editor-sidebar.collapsed {
  width: 50px;
}

.sidebar-header {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
}

.collapse-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #666;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
}

.tool-tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
}

.tab {
  padding: 10px 15px;
  cursor: pointer;
  user-select: none;
}

.tab.active {
  border-bottom: 2px solid #007bff;
  color: #007bff;
}

.tool-content {
  padding: 15px;
}

.tool-btn {
  display: block;
  width: 100%;
  padding: 8px 12px;
  margin-bottom: 8px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  text-align: left;
}

.tool-btn:hover {
  background-color: #f0f0f0;
}

/* 画布区域样式 */
.canvas-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f0f0f0;
  position: relative;
}

/* 顶部工具栏样式 */
.editor-toolbar {
  height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  padding: 0 10px;
  overflow-x: auto;
}

.toolbar-group {
  display: flex;
  align-items: center;
  padding: 0 5px;
  height: 40px;
}

.toolbar-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  color: #555;
  margin: 0 2px;
}

.toolbar-btn:hover {
  background-color: #f0f0f0;
  border-color: #ddd;
}

.toolbar-btn.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
  color: #1890ff;
}

.toolbar-btn.danger:hover {
  color: #ff4d4f;
  border-color: #ff4d4f;
  background-color: #fff1f0;
}

.toolbar-separator {
  width: 1px;
  height: 20px;
  background-color: #e0e0e0;
  margin: 0 5px;
}

.group-separator {
  width: 1px;
  height: 30px;
  background-color: #e0e0e0;
  margin: 0 8px;
}

.zoom-level {
  min-width: 45px;
  text-align: center;
  font-size: 12px;
  padding: 0 5px;
}

/* 标尺样式 */
.ruler {
  position: absolute;
  background-color: rgba(245, 245, 245, 0.5); /* 标尺背景透明度50% */
  z-index: 2;
}

.ruler-horizontal {
  top: 0;
  left: 20px;
  right: 0;
  height: 20px;
  border-bottom: 1px solid rgba(221, 221, 221, 0.5); /* 边框透明度50% */
}

.ruler-vertical {
  top: 20px;
  left: 0;
  bottom: 0;
  width: 20px;
  border-right: 1px solid rgba(221, 221, 221, 0.5); /* 边框透明度50% */
}

.ruler-corner {
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  height: 20px;
  background-color: rgba(245, 245, 245, 0.5); /* 角落透明度50% */
  border-right: 1px solid rgba(221, 221, 221, 0.5);
  border-bottom: 1px solid rgba(221, 221, 221, 0.5);
  z-index: 3;
}

.canvas-toolbar {
  height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  padding: 0 15px;
}

.tool-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.canvas-wrapper {
  flex: 1;
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e9ecef;
  padding: 0;
  box-sizing: border-box;
}

.canvas-wrapper.with-ruler {
  padding: 20px 0 0 20px; /* 标尺显示时添加边距，为水平和垂直标尺腾出空间 */
}

.fabric-editor {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  transition: all 0.3s ease;
  z-index: 1; /* 确保画布在标尺之上 */
}

/* 当显示标尺时修改fabric-editor的尺寸 */
.canvas-wrapper.with-ruler .fabric-editor {
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  margin: 0; /* 清除外边距 */
}

.canvas-info {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0,0,0,0.6);
  color: white;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  pointer-events: none;
}

/* 属性面板样式 */
.editor-properties {
  width: 320px;
  border-left: 1px solid #e0e0e0;
  transition: width 0.3s ease;
  position: relative;
  display: flex;
  flex-direction: column;
}

.editor-properties.collapsed {
  width: 0;
  border-left: none;
  overflow: visible; /* 改为visible确保按钮可见 */
}

.collapse-btn.right {
  position: absolute;
  left: -16px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 40px;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-right: none;
  border-radius: 4px 0 0 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
}

.properties-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.right-panel-tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f9f9f9;
}

.right-panel-tabs .tab {
  flex: 1;
  padding: 12px 10px;
  text-align: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.2s ease;
}

.right-panel-tabs .tab:hover {
  background-color: #f0f0f0;
  color: #333;
}

.right-panel-tabs .tab.active {
  color: #007bff;
  border-bottom-color: #007bff;
  font-weight: 500;
}

.right-panel-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #fff;
}

/* 属性面板内部样式微调 (可选) */
.prop-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
  font-weight: 500;
}

.prop-group {
  margin-bottom: 12px;
  font-size: 13px;
}

.prop-group label {
  display: inline-block;
  width: 50px;
  color: #666;
  margin-right: 5px;
}

.prop-group input[type="number"],
.prop-group input[type="range"] {
  padding: 4px 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
  font-size: 13px;
}

.prop-group input[type="number"] {
  width: 60px;
}

.prop-group input[type="range"] {
  width: 120px;
  vertical-align: middle;
}

/* 左侧栏样式增强 */
.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin: 15px 0 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-bottom: 15px;
}

.template-item {
  cursor: pointer;
  text-align: center;
  border: 1px solid transparent;
  transition: all 0.2s ease-in-out;
  padding: 5px;
  border-radius: 6px;
}

.template-item:hover {
  border-color: #007bff;
  background-color: #f8f9fa;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.template-preview {
  height: 80px;
  background-color: #f0f0f0;
  border-radius: 4px;
  margin-bottom: 5px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border: 1px solid #ddd;
  box-shadow: inset 0 0 5px rgba(0,0,0,0.1);
}

.template-item span {
  font-size: 12px;
  color: #666;
}

/* 模拟模板预览图 */
.commercial-template {
  background-image: linear-gradient(to bottom, #3498db, #2c3e50);
}

.social-template {
  background-image: linear-gradient(to bottom right, #e74c3c, #e67e22);
}

.laptop-template {
  background-image: linear-gradient(45deg, #2c3e50, #27ae60);
}

.phone-template {
  background-image: linear-gradient(to top, #8e44ad, #9b59b6);
}

.ecommerce-template {
  background-image: linear-gradient(to right, #f39c12, #d35400);
}

.promotion-template {
  background-image: linear-gradient(to bottom, #16a085, #2ecc71);
}

.product-template {
  background-image: linear-gradient(45deg, #3498db, #9b59b6);
}

.social-square-template {
  background-image: linear-gradient(to top right, #2980b9, #3498db);
}

.social-story-template {
  background-image: linear-gradient(to bottom left, #c0392b, #e74c3c);
}

.hands-template {
  background-image: url('https://picsum.photos/id/7/100/100');
  background-size: cover;
}

.shop-template {
  background-image: url('https://picsum.photos/id/27/100/100');
  background-size: cover;
}

.video-template {
  background-image: url('https://picsum.photos/id/39/100/100');
  background-size: cover;
}

.btn-create-blank {
  display: block;
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  margin-top: 15px;
  cursor: pointer;
  font-weight: 500;
  text-align: center;
}

.btn-create-blank:hover {
  background-color: #0069d9;
}

/* 文字面板样式 */
.text-card {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
  padding: 10px;
  cursor: pointer;
}

.text-card:hover {
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.2);
}

.text-title {
  font-size: 16px;
  margin-bottom: 5px;
}

.text-subtitle {
  font-size: 12px;
  color: #6c757d;
  text-align: right;
}

.text-format-tools {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.format-btn {
  width: 35px;
  height: 35px;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.format-btn:hover {
  background-color: #e9ecef;
}

.format-icon {
  font-size: 14px;
  line-height: 1;
}

.format-icon.bold {
  font-weight: bold;
}

.format-icon.italic {
  font-style: italic;
}

.format-icon.underline {
  text-decoration: underline;
}

.gradient-text {
  background-image: linear-gradient(45deg, #f3ec78, #af4261);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: bold;
}

.effects-card {
  text-align: center;
  padding: 15px;
}

/* 素材面板样式 */
.material-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-bottom: 15px;
}

.material-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.material-preview {
  width: 100%;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
  cursor: pointer;
  transition: transform 0.2s;
}

.material-preview:hover {
  transform: scale(1.05);
  border-color: #007bff;
}

.material-item span {
  font-size: 12px;
  margin-top: 5px;
  color: #666;
}

.upload-container {
  margin-bottom: 15px;
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 80px;
  background-color: #f8f9fa;
  border: 1px dashed #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.upload-btn:hover {
  background-color: #e9ecef;
  border-color: #adb5bd;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 5px;
  color: #6c757d;
}

.upload-desc {
  font-size: 11px;
  color: #6c757d;
  text-align: center;
  margin-top: 5px;
}

.background-options {
  margin-bottom: 15px;
}

.radio-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.radio-group input[type="radio"] {
  margin-right: 8px;
}

.color-picker-container {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #ddd;
}

/* 形状样式 */
.shape-rect {
  width: 40px;
  height: 40px;
  background-color: rgba(0,123,255,0.5);
  border: 1px solid #007bff;
}

.shape-circle {
  width: 40px;
  height: 40px;
  background-color: rgba(220,53,69,0.5);
  border: 1px solid #dc3545;
  border-radius: 50%;
}

.shape-triangle {
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-bottom: 40px solid rgba(255,193,7,0.5);
}

.shape-line {
  width: 50px;
  height: 2px;
  background-color: #6c757d;
}

.shape-polygon {
  width: 40px;
  height: 40px;
  background-color: rgba(153,50,204,0.5);
  clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
  border: 1px solid #9932cc;
}

/* 预览面板样式 */
.device-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 15px;
}

.device-item {
  text-align: center;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.device-item.active {
  border-color: #007bff;
  background-color: rgba(0,123,255,0.05);
}

.device-icon {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 5px;
}

.desktop-icon::before {
  content: "💻";
  font-size: 24px;
}

.tablet-icon::before {
  content: "📱";
  font-size: 24px;
}

.mobile-icon::before {
  content: "📱";
  font-size: 20px;
}

.device-size {
  font-size: 11px;
  color: #666;
  margin-top: 3px;
}

.size-inputs {
  display: flex;
  gap: 10px;
}

.input-group.half {
  flex: 1;
}

.checkbox-group {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.checkbox-group input {
  margin-right: 8px;
}

.preview-btn, .export-btn {
  display: block;
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  text-align: center;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  border: none;
}

.preview-btn {
  background-color: #f8f9fa;
  color: #212529;
  border: 1px solid #ddd;
}

.export-btn {
  background-color: #28a745;
  color: white;
}

.export-btn:hover {
  background-color: #218838;
}

/* 比例选择样式 */
.aspect-ratio-grid {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.ratio-item {
  flex: 1;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 8px 5px;
  cursor: pointer;
  background: white;
  margin: 0 3px;
  transition: all 0.2s ease-in-out;
}

.ratio-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.ratio-text {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 3px;
}

.ratio-size {
  font-size: 11px;
  color: #6c757d;
  line-height: 1.2;
}

/* 自定义尺寸样式 */
.custom-size {
  background-color: transparent;
  border: none;
  padding: 0;
}

.size-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.size-label {
  width: 75px;
  color: #6c757d;
}

.size-input {
  flex: 1;
  height: 32px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
}

.create-canvas-btn {
  height: 38px;
  font-size: 14px;
  transition: background-color 0.2s ease;
}

.create-canvas-btn:hover {
  background-color: #0069d9;
}

/* 商业模板和社交媒体模板图标样式 */
.template-icon-grid .template-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px 5px;
  height: 80px;
}

.template-icon {
  width: 36px;
  height: 36px;
  font-size: 20px;
  background-color: #e9ecef;
  border: none;
}

.template-icon-grid .template-item span {
  margin-top: 8px;
  font-size: 11px;
  line-height: 1.2;
  color: #495057;
}

.shop-icon::before {
  content: "🛒";
}

.promotion-icon::before {
  content: "🏷️";
}

.product-icon::before {
  content: "📱";
}

.mobile-icon::before {
  content: "📱";
}

.emoji-icon::before {
  content: "😀";
}

.video-icon::before {
  content: "🎬";
}

/* 图层面板样式 */
.layers-container {
  border: 1px solid #eaeaea;
  border-radius: 4px;
  overflow-y: auto;
  max-height: 300px;
  background: white;
}

.layer-item {
  display: flex;
  align-items: center;
  padding: 6px 10px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.layer-item:hover {
  background-color: #f5f5f5;
}

.layer-item.layer-selected {
  background-color: #e6f7ff;
}

.layer-visibility {
  margin-right: 8px;
  color: #999;
  cursor: pointer;
}

.layer-visibility i:hover {
  color: #1890ff;
}

.layer-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.layer-actions {
  display: flex;
  gap: 8px;
  color: #999;
}

.layer-actions i {
  cursor: pointer;
}

.layer-actions i:hover {
  color: #1890ff;
}

.layer-actions i.fa-lock {
  color: #1890ff;
}

.layer-actions i.fa-trash-alt:hover {
  color: #ff4d4f;
}

.layer-empty {
  padding: 20px;
  text-align: center;
  color: #999;
}

/* 字号控制样式 */
.size-controls {
  display: flex;
  align-items: center;
}

.size-btn {
  width: 30px;
  height: 30px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.size-input {
  flex: 1;
  text-align: center;
  margin: 0 5px;
  height: 30px;
  padding: 4px 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
}

/* 统一输入框组样式 */
.input-group {
  margin-bottom: 15px; /* 增加间距 */
}

.input-group label {
  display: block;
  margin-bottom: 6px; /* 调整标签下方间距 */
  font-size: 13px;
  color: #666;
}

.font-select,
.color-picker,
.size-input {
  width: 100%;
}

.color-picker {
  height: 34px; /* 统一高度 */
}

.font-select {
  height: 34px;
  padding: 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

/* 属性面板内的子标题 */
.prop-subtitle {
  font-size: 14px;
  font-weight: 500;
  color: #555;
  margin-top: 15px; /* 与上一组属性分隔 */
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

/* 输入框行内布局 */
.prop-row {
  display: flex;
  align-items: center;
  gap: 5px; /* 元素间距 */
}

/* 行内子标签 */
.prop-sub-label {
  width: 20px; /* 调整宽度 */
  text-align: right;
  font-size: 12px;
  color: #888;
}

/* 下拉选择框样式 */
.prop-select {
  width: 100%;
  height: 30px;
  padding: 0 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 13px;
}

/* 按钮组样式 */
.button-group {
  display: flex;
}

.button-group button {
  min-width: 30px;
  height: 30px;
  padding: 0 8px;
  margin-right: 5px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold; /* 让 B I U 更明显 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease, border-color 0.2s ease;
}

.button-group button:hover {
  background-color: #f0f0f0;
  border-color: #bbb;
}

.button-group button.active {
  background-color: #e0e0e0;
  border-color: #aaa;
  box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
}

.button-group button i {
  font-size: 14px; /* 图标大小 */
}

/* 描边行样式 */
.stroke-row input[type="color"] {
  flex-shrink: 0; /* 防止颜色选择器被压缩 */
}

/* 空状态提示 */
.prop-empty {
  text-align: center;
  padding: 30px 15px;
  color: #999;
}

.prop-empty .tip {
  font-size: 12px;
  margin-top: 10px;
  color: #aaa;
}

/* 圆角和阴影组缩进 */
.prop-group.indent {
  padding-left: 20px; /* 左侧缩进 */
}

.prop-group.indent label {
  width: 40px; /* 调整缩进后的标签宽度 */
}

/* 阴影复选框样式 */
.prop-group input[type="checkbox"] {
  margin-right: 8px;
  vertical-align: middle;
}

</style> 